////////////////////////////////////////////////////////////////////////////////
// Copyright 2006 CORE Solutions Limited
// All rights reserved.
// PROPRIETARY AND CONFIDENTIAL INFORMATION.
// Use is subject to license terms.
//
// FUNCTION ID      :   INQUIRY_JAVA
// AUTHOR           :   Alex Cheung 
// DATE CREATE      :   2006/02/03
// DESCRIPTION      :   a ACTION file for the function, INQUIRY_JAVA
//                  :   
//                  :   
//                  :   
//
// MODIFICATION HISTORY:
// DATE         AUTHOR          VERSION NO.         COMMENT
// -----------  --------------  ------------------  -------------------
// 2006/02/03   Alex Cheung     1.0                 source is generated.
//
//
//
////////////////////////////////////////////////////////////////////////////////

package com.erp.app.report.genericInquiry;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.erp.app.common.ProjectConstants;
import com.erp.app.report.genericInquiry.inquiryJava.criteria.InquiryJavaSrchCriteria;
import com.erp.app.report.genericInquiry.inquiryJava.vo.InquiryJavaVo;
import com.erp.framework.controller.action.SimplePageEditStyleAction;
import com.erp.framework.model.delegate.SimpleSearchMaintStyleDelegate;
import com.erp.framework.util.CommonUtil;
import com.erp.framework.util.logger.Logger;
import com.erp.framework.util.user.User;

/**
* A <strong>Page Edit Action</strong> is an adapter between the contents of an incoming
* HTTP request and the corresponding business logic that should be executed to
* process this request.  The controller (ActionServlet) will select an
* appropriate Action for each request.
* The main purpose for this action class is to handle the one-page document events
* from the web browsers.
*
* @author          Alex Cheung 
* @version 1.0     2006/02/03
* @since           FrameWork 1.0
*
*/
public class InquiryJavaAction extends SimplePageEditStyleAction {

	////////////////////////////////////////////////////////////////////////////////
	// CONSTANTS DEFINITION
	////////////////////////////////////////////////////////////////////////////////

	//public static final String ACTION_DO_SOMETHING = "actionDoSomething";
	//public static final String STATUS_DO_SOMETHING = "statusDoSomething";

	public static final String ACTION_ADD_ATTACH = "addAttach";
	public static final String ACTION_DEL_ATTACH = "rmAttach";
	public static final String ACTION_CHANGE_ATTACH = "chAttach";
	public static final String STATUS_ADD_ATTACH = ACTION_ADD_ATTACH;
	
	////////////////////////////////////////////////////////////////////////////////
	// GLOBAL VARIABLES DEFINITION
	////////////////////////////////////////////////////////////////////////////////



	////////////////////////////////////////////////////////////////////////////////
	// LOGICAL AND BUSINESS METHODS
	////////////////////////////////////////////////////////////////////////////////

	public ActionForward handlePageEvent(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		HttpSession session = request.getSession(false);
		InquiryJavaForm form = (InquiryJavaForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {
			if (!isHandled(request) && (action.equalsIgnoreCase(ACTION_ADD_ATTACH) || action.equalsIgnoreCase(ACTION_CHANGE_ATTACH))) {
				setHandled(request);
				actionForward = processActionAddAttach(mapping, formIn, request, response, errors);
			} else if (!isHandled(request) && (action.equalsIgnoreCase(ACTION_DEL_ATTACH))) {
				setHandled(request);
				actionForward = processActionDelAttach(mapping, formIn, request, response, errors);
				saveToken(request);
			}

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}

		return actionForward;
	}

	protected ActionForward processOtherStatus(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response,
		ActionErrors errors, String rb_status) {

		HttpSession session = request.getSession(false);
		InquiryJavaForm form = (InquiryJavaForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {
			if (rb_status.equals(STATUS_ADD_ATTACH)) {
				return processStatusAddAttach(mapping, formIn, request, response, errors, rb_status);
			}
		} catch (Exception e) {
			Logger.log(this, e);
		}

		return actionForward;
	}


	protected ActionForward processActionAddAttach(ActionMapping mapping,
	                                               ActionForm formIn,
	                                               HttpServletRequest request,
	                                               HttpServletResponse response,
	                                               ActionErrors errors) {
		HttpSession session = request.getSession(false);
		InquiryJavaForm form = (InquiryJavaForm) formIn;
		ActionForward actionForward = new ActionForward(mapping.getInput());
		String action = CommonUtil.nullToString(form.getPageEvent());

		session.setAttribute(GenericInquiryConstants.SESSION_HAS_LOGIN, ProjectConstants.GENERIC_YES);

		HashMap params = new HashMap();
		LinkedList keyList = new LinkedList();

		keyList.add("Line No.");
		keyList.add(form.getPageEventSrc());

		params.put(ProjectConstants.SESSION_KEY_LIST, keyList);
		params.put(ProjectConstants.SESSION_UPLOAD_FILE_SESSION_NAME, getSessionSimpleMastersStatus());
		params.put(ProjectConstants.SESSION_UPLOAD_FILE_SESSION_VALUE, STATUS_ADD_ATTACH);
		params.put(ProjectConstants.SESSION_OPENER_PATH, getFunctionId());
		params.put(ProjectConstants.SESSION_EVENTSRC, form.getPageEventSrc());
		params.put(GenericInquiryConstants.SESSION_UPLOAD_FILE_SKIP_CHECK_SIZE, ProjectConstants.GENERIC_YES);
		params.put(GenericInquiryConstants.SESSION_HAS_LOGIN, ProjectConstants.GENERIC_YES);
		session.setAttribute(ProjectConstants.SESSION_UPLOAD_FILE_PARAM, params);

		return actionForward;
	}

	private ActionForward processActionDelAttach(ActionMapping mapping,
	                                             ActionForm formIn,
	                                             HttpServletRequest request,
	                                             HttpServletResponse response,
	                                             ActionErrors errors) {
		HttpSession session = request.getSession(false);
		InquiryJavaForm form = (InquiryJavaForm) formIn;
		ActionForward actionForward = new ActionForward(mapping.getInput());

		try {
			int idx = Integer.parseInt(form.getPageEventSrc());
			
			ArrayList rows = form.getMultiRows();
			if (rows != null && rows.size() > 0) {
				InquiryJavaRow row = (InquiryJavaRow) rows.get(idx);
				row.setJavaSource(null);
			}
			
			
			
		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}

		return actionForward;
	}


	protected ActionForward processStatusAddAttach(ActionMapping mapping,
	                                               ActionForm formIn,
	                                               HttpServletRequest request,
	                                               HttpServletResponse response,
	                                               ActionErrors errors,
	                                               String rb_status) {
		HttpSession session = request.getSession(false);
		InquiryJavaForm form = (InquiryJavaForm) formIn;
		ActionForward actionForward = new ActionForward(mapping.getInput());

		try {
			HashMap params = (HashMap) session.getAttribute(ProjectConstants.SESSION_UPLOAD_FILE_RETURN_PARAM);
			session.removeAttribute(ProjectConstants.SESSION_UPLOAD_FILE_RETURN_PARAM);

			if (params == null)
				return actionForward;

			ArrayList rows = form.getMultiRows();
			
			FormFile file = (FormFile) params.get(ProjectConstants.SESSION_UPLOAD_FILE_RETURN_FORM_FILE);

			if (file == null)
				return actionForward;

			String evtSrc = (String) params.get(ProjectConstants.SESSION_EVENTSRC);
			int idx = Integer.parseInt(evtSrc);

			boolean isNew = CommonUtil.isEmpty(evtSrc);

			String fileName = file.getFileName();
			String contentType = file.getContentType();

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			InputStream stream = file.getInputStream();

			if (!CommonUtil.isEmpty(fileName)) {
				byte[] buffer = new byte[8192];
				int bytesRead = 0;

				while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
					baos.write(buffer, 0, bytesRead);
				}

				if (isNew) {
					InquiryJavaRow rowToAdd = new InquiryJavaRow();
					rowToAdd.setJavaSource(baos.toByteArray());
					form.addRow(rowToAdd);
				} else {
					InquiryJavaRow row = (InquiryJavaRow) rows.get(idx);
					row.setJavaSource(baos.toByteArray());
				}
			}
		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}

		return actionForward;
	}

	
	////////////////////////////////////////////////////////////////////////////////
	// END OF LOGICAL AND BUSINESS METHODS
	////////////////////////////////////////////////////////////////////////////////


	////////////////////////////////////////////////////////////////////////////////
	// OVERRIDES PARENT'S OPTIONAL METHODS
	////////////////////////////////////////////////////////////////////////////////

	//the following method is only to be overwritten by sub-class if intended
	//to set the aut-search on-load to on/off
	protected boolean getLoadOnEnter() {

		//auto-search when load
		return true;
	}

	//the following method is only to be overwritten by sub-class if intended
	//to set the clearing search result sets on-load to on/off
	protected boolean getResetOnEnter() {

		//reset last searched results when load 
		return false;
	}

	protected void initAction(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		super.initAction(mapping, formIn, request, response, errors);

//		HttpSession session = request.getSession(false);
//		InquiryJavaForm form = (InquiryJavaForm) formIn;
//		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
//		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {
//			HashMap errMsgMap = WebUtil.getModuleErrorMessages(editingUser.getCompanyCode(),
//				DBMENU_GENERAL_MENU, form.getModuleName(), form.getSysLangCode(), DBMENU_OBJECT_TYPE_ERR_MSG);
//			form.setErrMsgMap(errMsgMap);

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void initForm(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		super.initForm(mapping, formIn, request, response, errors);

//		HttpSession session = request.getSession(false);
//		InquiryJavaForm form = (InquiryJavaForm) formIn;
//		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
//		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void initPage(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		super.initPage(mapping, formIn, request, response, errors);

//		HttpSession session = request.getSession(false);
//		InquiryJavaForm form = (InquiryJavaForm) formIn;
//		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
//		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void beforeSearch(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

//		HttpSession session = request.getSession(false);
//		InquiryJavaForm form = (InquiryJavaForm) formIn;
//		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
//		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void afterSearch(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

//		HttpSession session = request.getSession(false);
//		InquiryJavaForm form = (InquiryJavaForm) formIn;
//		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
//		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void beforeSave(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

//		HttpSession session = request.getSession(false);
//		InquiryJavaForm form = (InquiryJavaForm) formIn;
//		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
//		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void afterSave(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		HttpSession session = request.getSession(false);
		InquiryJavaForm form = (InquiryJavaForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {
			ServletContext servletContext = getServlet().getServletContext();

			if (errors.size() == 0) {
				InquiryJavaSrchCriteria inqJavaCri = new InquiryJavaSrchCriteria();
				Set set = new HashSet();
				SimpleSearchMaintStyleDelegate dg = new SimpleSearchMaintStyleDelegate();
				
				clearCachedReports(formIn);

				ArrayList rows = (ArrayList) form.getMultiRows(0);

				for (int i = 0; rows != null && i < rows.size(); i++) {
				    InquiryJavaRow row = (InquiryJavaRow) rows.get(i);
					String inquiryType = row.getInquiryType();
					String javaType = row.getJavaType();

					String key = row.getUniqueKeyForCachedReport();
					
					if (set.contains(key))
						continue;

					set.add(key);

					inqJavaCri.setSrchInquiryTypeFr(inquiryType);
					inqJavaCri.setSrchInquiryTypeTo(inquiryType);
					inqJavaCri.setSrchJavaTypeFr(javaType);
					inqJavaCri.setSrchJavaTypeTo(javaType);

					InquiryJavaVo dummy = new InquiryJavaVo();
					Collection c = null;

					try {
						//c = dg.findByCriteria(dummy, inqJavaCri, editingUser.getUserId() );
	                    c = dg.findByCriteria(dummy, inqJavaCri);
					} catch (Exception e) {
						Logger.logExceptions(this, e);
					}
					
					if (c != null) {
						servletContext.setAttribute(key, c);
					}				
				}
			}
		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	/**
	 * Look for all attributes in servlet context with keys corresponding with the
	 * unique IDs of the GenericInquiryJavaRow, and null them all
	 * 
	 * @param formIn
	 */
	private void clearCachedReports(ActionForm formIn) {
		InquiryJavaForm form = (InquiryJavaForm)formIn;
		ServletContext sc = getServlet().getServletContext();
		
		Collection list = form.getMultiRows(0);
		Set set = new HashSet();
		
		for (Iterator it = list.iterator(); it.hasNext();) {
			InquiryJavaRow row = (InquiryJavaRow)it.next();	
			
			String key = row.getUniqueKeyPrefixForCachedReport();
			
			if (set.contains(key))
				continue;
			
			set.add(key);
			
			Collection java_types = getJavaTypes();
			for (Iterator it2 = java_types.iterator(); it2.hasNext();) {
				String supported_java_type = (String)it2.next();
				
				sc.removeAttribute(key + "." + supported_java_type);
			}
		}
	}

	/**
	 * Return a list of java types that need to be cleaned up in the servlet context
	 * before we reload everything.  
	 * 
	 * *NOTES* This list should reflect the types of report you can support.  Please
	 * modify this accordingly
	 * 
	 * @return a collection of java types
	 */
	private Collection getJavaTypes() {
		Collection c = new ArrayList();
		
		c.add(GenericInquiryConstants.JAVA_TYPE_CSV);
		c.add(GenericInquiryConstants.JAVA_TYPE_EXCEL);
		c.add(GenericInquiryConstants.JAVA_TYPE_HTM);
		c.add(GenericInquiryConstants.JAVA_TYPE_PDF);
		
		return c;
	}
	
	protected void beforeRefresh(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

//		HttpSession session = request.getSession(false);
//		InquiryJavaForm form = (InquiryJavaForm) formIn;
//		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
//		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void afterRefresh(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

//		HttpSession session = request.getSession(false);
//		InquiryJavaForm form = (InquiryJavaForm) formIn;
//		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
//		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void beforeAddRow(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

//		HttpSession session = request.getSession(false);
//		InquiryJavaForm form = (InquiryJavaForm) formIn;
//		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
//		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}


		//TODO: Add the following line to ProjectSecurityConstants.java
		//public static final String SP_SHARE_INQUIRY_JAVA = "SP_SHARE_INQUIRY_JAVA";
	protected void afterAddRow(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

//		HttpSession session = request.getSession(false);
//		InquiryJavaForm form = (InquiryJavaForm) formIn;
//		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
//		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {
			
		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void beforeDeleteRow(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

//		HttpSession session = request.getSession(false);
//		InquiryJavaForm form = (InquiryJavaForm) formIn;
//		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
//		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void afterDeleteRow(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

//		HttpSession session = request.getSession(false);
//		InquiryJavaForm form = (InquiryJavaForm) formIn;
//		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
//		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected String getSimpleSrchMenuId() {

		//TODO: Add the following line to ProjectMenuConstants.java
		//public static final String MOD_INQUIRY_JAVA = "MOD_INQUIRY_JAVA";
		return ProjectConstants.MOD_INQUIRY_JAVA;
	}

	////////////////////////////////////////////////////////////////////////////////
	// END OF OPTIONAL METHODS
	////////////////////////////////////////////////////////////////////////////////


	////////////////////////////////////////////////////////////////////////////////
	// IMPLEMENTS PARENT'S ABSTRACT METHODS
	////////////////////////////////////////////////////////////////////////////////

	protected String getModuleName(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request,HttpServletResponse response) {

		//TODO: Add the following line to ProjectMenuConstants.java
		//public static final String MOD_INQUIRY_JAVA = "MOD_INQUIRY_JAVA";
		return ProjectConstants.MOD_INQUIRY_JAVA;
	}

	protected String getFunctionId() {

		//struts-config xxxxx.do
		return "inquiryJava.do";
	}

	protected void setFormType(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
		 HttpServletResponse response, ActionErrors errors) {

		InquiryJavaForm form = (InquiryJavaForm) formIn;
		form.setFormType(ProjectConstants.FORM_TYPE_PAGE_EDIT);
	}

	protected String getMasterDelegateName() {

		//the corresponding delegate session name
		return "inquiryJavaDelegate";
	}

	protected Class getMasterFormClass() {

		//the corresponding form class
		return InquiryJavaForm.class;
	}

	protected Class getMasterVOClass() {

		//corresponding master vo class
		return InquiryJavaVo.class;
	}

	protected Class getDetailVOClass() {

		//corresponding detail vo class
		return InquiryJavaVo.class;
	}

	protected Class getDetailFormClass() {
		//corresponding detail row class
		return InquiryJavaRow.class;
	}

	protected String getDetailFormSessionName() {

		//corresponding detail form session name
		return "inquiryJavaForm";
	}

	protected Class getSearchCriteriaClass() {

		//corresponding searching criteria class
		return InquiryJavaSrchCriteria.class;
	}

	protected void setOtherCriteria(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response,
		ActionErrors errors, Object criteria) {

		HttpSession session = request.getSession(false);
		User user = (User) session.getAttribute(ProjectConstants.SESSION_USER);
		InquiryJavaSrchCriteria crit = (InquiryJavaSrchCriteria) criteria;

		crit.setSearchResult(true);
	}

	////////////////////////////////////////////////////////////////////////////////
	// END OF ABSTRACT METHODS
	////////////////////////////////////////////////////////////////////////////////
}
